def parse_email(email):
    """解析邮箱获取用户名和域名"""
    if "@" not in email:
        raise ValueError(f"无效的邮箱格式: {email}")
    username, domain = email.split("@", 1)  # 只分割一次，处理极端情况
    return username, domain


def main():
    # 读取联系人数据
    contacts = []
    with open("contacts.txt", "r", encoding="utf-8") as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:  # 跳过空行
                continue
            parts = line.split()
            if len(parts) != 3:
                raise ValueError(
                    f"第{line_num}行格式错误，需要3个字段，实际有{len(parts)}个"
                )

            name, gender, email = parts
            username, domain = parse_email(email)

            contacts.append(
                {
                    "name": name,
                    "gender": gender,
                    "email": email,
                    "username": username,
                    "domain": domain,
                }
            )

    # 排序：先按域名，再按用户名
    contacts.sort(key=lambda x: (x["domain"], x["username"]))

    # 生成输出内容
    output_lines = []
    for contact in contacts:
        # 确定称呼
        title = "先生" if contact["gender"] == "男" else "女士"
        # 构建邮件内容
        output_lines.append(f"to: <{contact['email']}>")
        output_lines.append(
            f"尊敬的{contact['name']}{title}，您的会员资格即将到期，请及时续费。"
        )
        output_lines.append("---")

    # 写入输出文件（移除最后一个多余的分隔线）
    with open("emails.txt", "w", encoding="utf-8") as f:
        f.write("\n".join(output_lines))
        f.write("\n")


if __name__ == "__main__":
    main()
